/**
 * @file
 * @auth jinguangguo
 * @date 2017/1/23
 */

import Vue from 'vue';
import cookie from '../../../grsc-base/util/cookie';
import parseUrl from '../../../grsc-base/util/parseUrl';
import commonService from '../../common/commonService';
import lib from '../../common/lib';
import Loading from '../../../grsc-base/component/Loading.vue';
import WebBox from '../../component/WebBox/WebBox';
import Validator from '../../../grsc-base/component/Validator/main';
import agreement from './agreement.vue';
import address from '../../mixins/tel';
import {
    REG_EMAIL,
    REG_LOGPWD,
    REG_PAYPWD,
    REG_PHONE,
    REG_EMAIL_PHONE
} from '../../../grsc-base/common/constants';

import tpl from './tpl.html';
import service from './service';

let query = parseUrl();
let inviteCode = '';
let noCode = false;
if (query.r) {
    inviteCode = query.r;
    noCode = query.d ? true : false;
}

if (inviteCode) {
    lib.isGoMobilePage('m_register.html?r=' + inviteCode);
} else {
    lib.isGoMobilePage('m_register.html');
}

const isNeedStat = lib.isNeedStat();

// if(lib.isMobile() && window.location.href.indexOf('m_register.html') < 0){
//     // 移动端跳转
//     window.location.href = 'm_register.html';
// }

export default Vue.extend({
    template: tpl,
    components: {
        Loading,
        Validator,
        WebBox,
        agreement
    },
    data() {
        return {
            lib: lib,
            hasAgree: false,
            noCode: noCode,
            isCountry: false,
            rotate: true,
            form: {
                phone: '',
                email: '',
                setPsd: '',
                confirmNewPwd: '',
                inviteCode: inviteCode,
                addressList: address,
                areaCode: '86',
                imgCode: '',
                identifyingCode: '',
            },
            rules: {
                phone: {
                    tip: "",
                    required: true,
                    requiredTip: '请输入手机号码',
                    pattern: REG_PHONE,
                    patternTip: '手机号码不正确'
                },
                imgCode: {
                    required: true,
                    requiredTip: this.$t('common.captchaRequireTip')
                },
                identifyingCode: {
                    required: true,
                    requiredTip: this.$t('common.verifyCodeRequireTip'),
                    pattern: '\\d{6}',
                    patternTip: window.CODE.IDENTIFY[this.$i18n.locale]
                },
                email: {
                    tip: "",
                    required: true,
                    requiredTip: this.$t('common.emailRequireTip'),
                    pattern: REG_EMAIL,
                    patternTip: window.CODE.EMAIL[this.$i18n.locale]
                },
                setPsd: {
                    required: true,
                    requiredTip: this.$t('common.loginPassRequireTip'),
                    minlength: 6,
                    minlengthTip: this.$t('common.ruleLoginPassLength'),
                    maxlength: 20,
                    maxlengthTip: this.$t('common.ruleLoginPassLength'),
                    pattern: REG_LOGPWD,
                    patternTip: this.$t('common.ruleLoginPassPattern')
                },
                confirmNewPwd: {
                    required: true,
                    requiredTip: this.$t('common.repeatPassRequireTip'),
                    equalTo: 'setPsd',
                    equalToTip: this.$t('common.passEqualTip')
                }
            },
            isLoading: true,
            isRequesting: false,
            imgCodeSrc: '',
            randomKey: '',
            codeBtnText: this.$t('common.sendEmail'),
            sendingCode: false,
            codeLock: false,
            type: 'phone',
            isAgree: false,
        }
    },
    created() {
        this.changeImgCode();
    },
    watch: {
        type() {
            this.form = {
                phone: '',
                email: '',
                setPsd: '',
                confirmNewPwd: '',
                inviteCode: inviteCode,
                imgCode: '',
                identifyingCode: '',
            }
        }
    },
    mounted() {
        // ued体验优化
        setTimeout(() => {
            this.isLoading = false;
        }, 500)
    },
    methods: {
        /**
         * 短信验证码
         */
        sendCode() {
            this.rules.phone.$check();

            if (this.form.imgCode === '') {
                this.rules.imgCode.$setError(this.$t('common.captchaRequireTip'));
            }

            if (this.rules.phone.$valid === false || this.form.imgCode === '') {
                return;
            }

            let that = this;
            let loopTimeId = null;
            let count = 60;

            //登录后发送验证码不需要手机号信息
            this.sendingCode = true;
            commonService.sendCode({
                sendType:"PHONE",
                sendAccount:this.form.phone,
            }, {
                'captchar-code': this.form.imgCode,
                'captchar-no': this.randomKey,
                'area-code': this.form.areaCode,
            }).done((rep) => {
                if (rep.code == window.CODE.SUCCESS) {
                    window.success('验证码发送成功');
                    this.codeLock = true; //获取验证码锁定 true：正在获取验证码，不可点击   false：可以点击
                    this.rules.identifyingCode.$setRight(window.CODE.IDENTIFY_HAS_SEND[this.$i18n.locale]);
                    send();
                    loopTimeId = setInterval(function () {
                        send();
                    }, 1000)
                } else if (rep.code === window.CODE.EMAIL.CODE) {
                    this.changeImgCode();
                    this.rules.email.$setError(window.CODE.EMAIL[this.$i18n.locale]);
                } else if (rep.code === window.CODE.CAPTCHA.CODE) {
                    this.changeImgCode();
                    this.rules.imgCode.$setError(window.CODE.CAPTCHA[this.$i18n.locale]);
                } else if (rep.code === window.CODE.CAPTCHA_INVALID.CODE) {
                    this.rules.imgCode.$setError(window.CODE.CAPTCHA_INVALID[this.$i18n.locale]);
                } else if (rep.code === window.CODE.IDENTIFY_HAS_SEND.CODE) {
                    this.rules.identifyingCode.$setError(window.CODE.IDENTIFY_HAS_SEND[this.$i18n.locale]);
                }
            }).fail((rep) => {
                window.error(rep.msg);
            }).always(() => {
                this.sendingCode = false;
            });

            function send() {
                if (count > 0) {
                    that.codeBtnText = count + that.$t('common.secondUnit');
                    count--;
                } else {
                    clearInterval(loopTimeId);
                    that.codeBtnText = that.$t('common.retryVerifyCode');
                    that.codeLock = false;
                }
            }

        },

        /**
         * 改变图形验证码
         */
        changeImgCode() {
            this.randomKey = new Date().getTime();
            commonService.getCode({
                randomKey: this.randomKey
            }).done(rep => {
                this.imgCodeSrc = rep;
            });
        },

        changeAgree($event) {
            if ($event.target.checked === true) {
                this.hasAgree = true;
            } else {
                this.hasAgree = false;
            }
        },

        agreement() {
            this.$refs.agree.open();
        },

        /**
         * 验证注册密码
         */
        checkPsd() {
            this.rules.setPsd.tip = this.$t('common.ruleLoginPassLength');
            if (isNeedStat) {
                lib.stat(['_trackEvent', '注册', '第一次输入密码Input获取焦点']);
            }
        },
        checkPsdBlur() {
            this.rules.setPsd.tip = '';
        },

        // 邮箱
        statEmail() {
            if (isNeedStat) {
                lib.stat(['_trackEvent', '注册', '邮箱Input获取焦点']);
            }
        },

        select() {
            this.isCountry = !this.isCountry;
            this.rotate = !this.rotate;
        },
        // 再次确定
        reCheckPsd() {
            if (isNeedStat) {
                lib.stat(['_trackEvent', '注册', '再次输入密码Input获取焦点']);
            }
        },
        country(tel) {
            this.form.areaCode = tel;
            this.rotate = true;
            this.isCountry = false;
        },

        /**
         * 注册验证
         */
        submit() {
            if (this.rules.$checkAll() === false) {
                return;
            }
            let that = this;
            if (this.type == 'phone') {
                this.isRegisting = true;
                let params = {
                    loginPassword: this.form.setPsd,
                    lang: '/' + this.$i18n.locale
                };
                if ($.trim(this.form.inviteCode)) {
                    params.refereeCode = this.form.inviteCode;
                }
                service.phoneAccount(params, {
                    'account-no': this.form.phone,
                    'service-code': this.form.identifyingCode,
                    'area-code': this.form.areaCode
                }).done(rep => {
                    if (rep.code === window.CODE.SUCCESS) {
                        window.success('注册成功', () => {
                            window.location.href = './login.html';
                        })
                    } else {
                        this.isRegisting = false;
                        window.error(rep.msg);
                    }
                })
                return false;
            }

            let params = {
                loginPassword: this.form.setPsd,
                lang: '/' + this.$i18n.locale
            };

            if ($.trim(this.form.inviteCode)) {
                params.refereeCode = this.form.inviteCode;
            }

            let header = {
                'account-no': this.form.email,
            };

            this.isRegisting = true;
            service.preRegister(params, header).done((rep) => {
                if (isNeedStat) {
                    lib.stat(['_trackEvent', '注册', '立即注册点击']);
                }
                if (rep.code === window.CODE.SUCCESS) {
                    // lib.doLogin(rep.data.token, this.form.email, false);

                    this.$router.push({
                        path: '/confirm',
                        params: {
                            account: this.form.email
                        }
                    });

                    // 注册代表进行了登录
                    // cookie.set('LOGIN_TOKEN', 1 ,{path:'/'});
                    // window.localStorage.setItem('account-no', this.form.email);
                } else {
                    this.isRegisting = false;
                    if (rep.code === window.CODE.HAS_REGISTER.CODE) {
                        this.rules.email.$setError(window.CODE.HAS_REGISTER[this.$i18n.locale]);
                    } else if (rep.code === window.CODE.REGISTER_MORE_TIMES.CODE) {
                        window.error(window.CODE.REGISTER_MORE_TIMES[this.$i18n.locale]);
                    } else {
                        window.error(rep.msg);
                    }
                }
            });
        },
        goToLogin() {
            if (isNeedStat) {
                lib.stat(['_trackEvent', '注册', '立即注册点击'], () => {
                    window.location.href = './login.html';
                });
            }

        }
    }
});